package com.adjaisd.scarecrow.common.config.auth;

import com.adjaisd.scarecrow.common.utils.jwt.JwtUtils;
import com.adjaisd.scarecrow.service.RedisService;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        try {
            String token = request.getHeader("X-token");
            //token验证
            if (JwtUtils.checkToken(token)) {
                Claims claims = JwtUtils.getMembers(token);
                System.out.println(request.getRequestURL());
                System.out.println("claims = " + claims);

                long id = Long.parseLong(claims.get("id").toString());
                String key = "token" + id;

                // 是否存在key或val与token是否一致
                if (!redisService.existKey(key) || !redisService.equalVal(key, token)) {
                    returnError(response, 50014, 403, "未登录");
                    return false;
                }

                if (!redisService.isOverdue(key)) { // key是否过期
                    redisService.update(key, 5);
                    return true;
                } else {
                    returnError(response, 50014, 403, "登陆过期");
                    return false;
                }
            } else {
                System.out.println("非法URL : " +request.getRequestURL());
                returnError(response, 50008, 403, "非法的token");
                return false;
            }
        } catch (Exception e) {
            response.setStatus(403);
            return false;
        }
    }

    private void returnError(HttpServletResponse response, int commCode, int status, String msg) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            PrintWriter out = response.getWriter();
            JSONObject res = new JSONObject();
            res.put("code", commCode);
            if (msg != null || !msg.equals(""))
                res.put("message", msg);
            out.append(res.toString());
            response.setStatus(status);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(status);
        }
    }

}